import { Card, Button, Table, message, Drawer, Form, Input, Cascader, Modal } from 'antd';
import React, { Component } from 'react';
import memory from '../../utils/memory';
import store from '../../store';
import { reqAddRole, reqRole, setPower } from '../../api/roleAPI';

class Role extends Component {
    constructor() {
        super();
        this.state = {
            isLoading: store.getState().isLoading,
            isModalVisible: false,// 对话框
            tempMenu: [],
            role: {},//选中的角色
            visible: false,
            tableData: [], // 表格数据
            columns: [
                {
                    title: '编号',
                    dataIndex: 'id',
                    key: 'id',
                },
                {
                    title: '角色名称',
                    dataIndex: 'username',
                    key: 'username',
                },
                {
                    title: '创建时间',
                    dataIndex: 'createTime',
                    key: 'createTime',
                    render: (text) => {
                        return new Date(parseInt(text) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ');
                    }
                },
                {
                    title: '授权人',
                    dataIndex: 'createPerson',
                    key: 'createPerson',
                },
            ],
            options: [ //级联选择
                {
                    label: '主页',
                    value: '/home',
                },
                {
                    label: '商品类别管理',
                    value: '/category',
                },

                {
                    label: '商品管理',
                    value: "/product",
                },
                {
                    label: '用户管理',
                    value: "/user",
                },
                {
                    label: '角色管理',
                    value: "/role",
                },
                {
                    label: '柱状图',
                    value: "/bar",
                },
                {
                    label: '线状图',
                    value: "/line",
                },

            ]
        }
    }
    // 级联选择框
    onChange = (value) => {
        this.setState({
            tempMenu: value
        })
        let value2 = value.map(item => {
            return item[0]
        })
        this.setState({
            role: {
                ...this.state.role,
                menu: value2
            }
        })
    }
    // 抽屉
    showDrawer = () => {
        this.setState({
            visible: true
        })
    };
    onClose = () => {
        this.setState({
            visible: false
        })
    }
    // 抽屉-确认添加
    onFinish = async (value) => {
        value.createPerson = memory.user.username;
        value.createTime = (+new Date()) / 1000;
        value.menu = [];
        // 后端添加
        let res = await reqAddRole(value);
        console.log(res);
        if (res.data) {
            //前端添加
            this.setState({
                tableData: [
                    ...this.state.tableData, value
                ]
            }, () => {
                let inp = document.querySelectorAll('.inp');
                console.log(inp);
                for (let i = 0; i < inp.length; i++) {
                    inp[i].value = '';
                }
                message.success('添加成功')
            })
        } else {
            message.error('添加失败')
        }
    }
    onFinishFailed = (value) => {
        console.log(value);
    }
    // 单击行选中
    onRow = (role) => {
        return {
            onClick: () => {
                let tMenu = role.menu.map(item => {
                    return [item];
                })
                this.setState({
                    role,
                    tempMenu: tMenu
                })
            }
        }
    }
    // 控制级联对话框的显示隐藏
    showModal = () => {
        this.setState({
            isModalVisible: true
        })
    };
    handleCancel = () => {
        this.setState({
            isModalVisible: false
        })
    };
    // 确认改变权限
    handleOk = () => {
        const { role } = this.state;
        console.log(role);
        setPower(role.id, role).then(res => {
            console.log(res);
        })
        // this.setState({
        //     isModalVisible: false
        // })
    };
    async componentDidMount() {

        try {
            store.subscribe(() => {
                this.setState({
                    isLoading: store.getState().isLoading
                })
            });
            let res = await reqRole();
            if (res.data.length > 0) {
                res.data.shift();
                this.setState({
                    tableData: res.data
                })
            } else {
                message.error('请求出错')
            }
        } catch (error) {
            message.error('请求出错');
            console.log(error);
        }
    }
    render() {

        const title = (<>
            <Button
                style={{ margin: '0 10px' }}
                type="primary"
                onClick={this.showDrawer}
            >创建角色</Button>
            <Button
                type="primary"
                onClick={this.showModal}
                disabled={!this.state.role.id}
            >设置角色权限</Button>
        </>)
        return (
            <>
                <Card title={title}>
                    <Table
                        loading={this.state.isLoading}
                        bordered
                        onRow={this.onRow}
                        rowSelection={{ type: 'radio', selectedRowKeys: [this.state.role.id] }}
                        dataSource={this.state.tableData}
                        columns={this.state.columns}
                        rowKey='id'
                    ></Table>
                </Card>
                <Drawer
                    size='large'
                    title="创建一个新角色"
                    placement="right"
                    onClose={this.onClose}
                    visible={this.state.visible}
                >
                    <Form
                        name="basic"
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 12 }}
                        initialValues={{ remember: true }}
                        onFinish={this.onFinish}
                        onFinishFailed={this.onFinishFailed}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="编号"
                            name="id"
                            rules={[{ required: true, message: '编号不能为空' }]}
                        >
                            <Input className='inp' />
                        </Form.Item>
                        <Form.Item
                            label="名称"
                            name="username"
                            rules={[{ required: true, message: '名称不能为空' }]}
                        >
                            <Input className='inp' />
                        </Form.Item>
                        <Form.Item
                            label="密码"
                            name="password"
                            rules={[{ required: true, message: '密码不能为空!' }]}
                        >
                            <Input type='password' className='inp' />
                        </Form.Item>

                        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                            <Button type="primary" htmlType="submit">
                                保存
                            </Button>
                        </Form.Item>
                    </Form>
                </Drawer>
                <Modal title="权限设置"
                    visible={this.state.isModalVisible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    cancelText='取消'
                    okText='确认'
                >
                    <Cascader
                        style={{ width: '80%', marginLeft: '10%' }}
                        options={this.state.options}
                        onChange={this.onChange}
                        multiple
                        value={this.state.tempMenu}
                        maxTagCount="responsive"
                    />
                </Modal>
            </>
        );
    }
}

export default Role;